package com.fate.system.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fate.framework.dto.IdParamDTO;
import com.fate.framework.utils.CommonUtil;
import com.fate.system.utils.*;
import com.fate.framework.utils.SystemUtil;
import com.fate.system.dto.filedetail.FileDetailAddDTO;
import com.fate.system.dto.filedetail.FileDetailPageDTO;
import com.fate.system.dto.filedetail.FileDetailUpdateDTO;
import com.fate.system.dto.tencent.TencentDTO;
import com.fate.system.entity.FileDetail;
import com.fate.system.service.IFileDetailService;
import com.fate.system.service.ITencentService;
import com.fate.system.vo.filedetail.FileDetailListVO;
import com.fate.system.vo.filedetail.FileDetailDetailVO;
import com.fate.system.vo.tencent.FormatImageVO;
import com.fate.system.vo.tencent.TencentImageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

import static com.fate.system.utils.FileTransformUtil.getFileExtension;

@Tag(name = "文件操作 API")
@RestController
@RequestMapping("/api/v1.0/fileDetail")
public class FileDetailController {

  @Resource private IFileDetailService fileDetailService;
  @Resource private FileStorageService fileStorageService;
  @Resource private ITencentService tencentService;

  /** 上传文件 */
  @SaIgnore
  @Operation(summary = "上传文件")
  @PostMapping("/upload")
  public FileInfo upload(MultipartFile file) throws Exception {
    FileInfo upload = fileStorageService.of(file).upload();
    Map<String, String> map = new HashMap<>();
    int numberOfPages = 0;

    String fileName = file.getOriginalFilename();
    if (fileName != null) {
      String extension = getFileExtension(fileName).toLowerCase();

      numberOfPages =
          switch (extension) {
            case "docx" -> FilePagesUtil.getDocxPageCount(file.getInputStream());
            case "doc" -> FilePagesUtil.getDocPageCount(file.getInputStream());
            case "xlsx", "xls" -> {
              MultipartFile multipartFile = FileTransformUtil.convertToPdf(file);
              yield PdfUtil.getNumberOfPages(multipartFile);
            }
            case "pptx" -> FilePagesUtil.getPptxSlideCount(file.getInputStream());
            case "ppt" -> FilePagesUtil.getPptSlideCount(file.getInputStream());
            case "pdf" -> PdfUtil.getNumberOfPages(file);
            default -> 1;
          };
    }

    map.put("numberOfPages", String.valueOf(numberOfPages));
    upload.setThMetadata(map);
    return upload;
  }

  @SaIgnore
  @Operation(summary = "上传文件（office全部转pdf）")
  @PostMapping("/upload2Pdf")
  public FileInfo upload2Pdf(MultipartFile file) throws Exception {
    MultipartFile multipartFile = FileTransformUtil.convertToPdf(file);
    String originalFilename = multipartFile.getOriginalFilename();
    int numberOfPages = 0;
    if (CommonUtil.notNullOrEmpty(originalFilename)
        && getFileExtension(originalFilename).equals("pdf")) {
      numberOfPages = PdfUtil.getNumberOfPages(multipartFile);
    }
    FileInfo upload = fileStorageService.of(multipartFile).upload();
    Map<String, String> map = new HashMap<>();
    map.put("numberOfPages", String.valueOf(numberOfPages));
    upload.setThMetadata(map);
    return upload;
  }

  @Operation(summary = "新增")
  @PostMapping("/add")
  public void add(@RequestBody @Valid FileDetailAddDTO addDTO) {
    FileDetail fileDetail = SystemUtil.buildResource(addDTO, FileDetail.class);
    fileDetailService.save(fileDetail);
  }

  @Operation(summary = "删除")
  @PostMapping("/remove")
  public void remove(@RequestBody @Valid IdParamDTO idParamDTO) {
    fileDetailService.removeById(idParamDTO.getId());
  }

  @Operation(summary = "更新")
  @PostMapping("/update")
  public void update(@RequestBody @Valid FileDetailUpdateDTO updateDTO) {
    FileDetail fileDetail = SystemUtil.buildResource(updateDTO, FileDetail.class);
    fileDetailService.updateById(fileDetail);
  }

  @Operation(summary = "详情")
  @PostMapping("/detail")
  public FileDetailDetailVO detail(@RequestBody @Valid IdParamDTO idParamDTO) {
    FileDetail fileDetail = fileDetailService.getById(idParamDTO.getId());
    return SystemUtil.buildResource(fileDetail, FileDetailDetailVO.class);
  }

  @Operation(summary = "分页列表")
  @PostMapping("/getPageList")
  public Page<FileDetailListVO> getPageList(@RequestBody @Valid FileDetailPageDTO pageDTO) {
    Page<FileDetail> page = fileDetailService.getPageList(pageDTO);
    return SystemUtil.buildResource(page, FileDetailListVO.class);
  }

  @SaIgnore
  @Operation(summary = "转换文件（换底）")
  @PostMapping("/transferImage")
  public FormatImageVO transferImage(@RequestBody @Valid TencentDTO tencentDTO) {
    TencentImageVO tencentImageVO = tencentService.transferImage(tencentDTO.getBase64());
    FormatImageVO formatImageVO =
        FillPicture.fillPicture(
            tencentImageVO.getResultImage(),
            new Color(tencentDTO.getR(), tencentDTO.getG(), tencentDTO.getB()),
            tencentDTO.getSize());
    FormatImageVO formatImageVOAlbum =
        PhotoLayoutGenerator.generatePhotoLayout(formatImageVO.getBase64(), tencentDTO.getSize());
    formatImageVO.setAlbumPic(formatImageVOAlbum.getAlbumPic());
    formatImageVO.setAlbumWidth(formatImageVOAlbum.getAlbumWidth());
    formatImageVO.setAlbumHeight(formatImageVOAlbum.getAlbumHeight());
    return formatImageVO;
  }
}
